package org.wang.generalcode.modules.sys.dict.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.wang.generalcode.modules.sys.pojo.entity.DictItem;
import org.wang.generalcode.modules.sys.service.IDictItemService;
import org.wang.generalcode.support.trans.core.annotation.Dictionary;
import org.wang.generalcode.support.trans.core.entity.ExtendParam;
import org.wang.generalcode.support.trans.core.service.Translatable;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.wang.generalcode.modules.sys.constant.CacheConstants.DICT_CODE_PREFIX;

@Slf4j
@Component
public class DictTranslateServiceImpl implements Translatable {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private IDictItemService dictItemService;

    @Override
    public List<Object> translate(String origin, Dictionary dictConfig, ExtendParam extendParam) {
        if (StrUtil.isBlank(origin)) {
            return new ArrayList<>();
        }

        try {
            final String condition = extendParam.getConditionValue();
            
            // 处理可能的转义字符
            String jsonStr = origin.replace("\\\"", "\"");
            
            // 如果是JSON数组格式，需要解析并分别翻译
            if (JSONUtil.isTypeJSON(jsonStr)) {
                JSONArray jsonArray = JSONUtil.parseArray(jsonStr);
                List<String> translatedList = new ArrayList<>();
                for (Object item : jsonArray) {
                    String value = String.valueOf(item);
                    String translatedValue = translateSingle(value, condition);
                    if (translatedValue != null) {
                        translatedList.add(translatedValue);
                    }
                }
                return List.of(JSONUtil.toJsonStr(translatedList));
            }
            
            // 单个值的翻译
            String translatedValue = translateSingle(origin, condition);
            return List.of(translatedValue != null ? translatedValue : origin);
        } catch (Exception e) {
            log.error("翻译失败，原始值: {}, 错误: {}", origin, e.getMessage());
            return List.of(origin);
        }
    }
    
    private String translateSingle(String value, String condition) {
        if (StrUtil.isBlank(value)) {
            return value;
        }
        
        try {
            // 先从Redis缓存中获取
            Object cached = redisTemplate.opsForValue().get(DICT_CODE_PREFIX + condition + ":" + value);
            if (!StrUtil.isEmptyIfStr(cached)) {
                return String.valueOf(cached);
            }
            
            // 缓存中没有，从数据库查询
            DictItem result = dictItemService.getDictValue(condition, value);
            if (result != null) {
                String name = result.getName();
                // 将结果存入Redis缓存
                redisTemplate.opsForValue().set(DICT_CODE_PREFIX + condition + ":" + value, name);
                return name;
            }
        } catch (Exception e) {
            log.error("单个值翻译失败，值: {}, 条件: {}, 错误: {}", value, condition, e.getMessage());
        }
        
        return value; // 如果没有找到对应的翻译或发生错误，返回原值
    }
}
